import React, { Component } from 'react'
import PropTypes from 'prop-types'
import LazyLoad from "vanilla-lazyload"
import lazyloadConfig from './config'
import './index.module.scss'
if (!document.lazyLoadInstance) {
    document.lazyLoadInstance = new LazyLoad(lazyloadConfig)
}

export default class LazyImage extends Component {
    picRef = React.createRef()
    imgRef = React.createRef()

    static propTypes = {
        webp: PropTypes.bool,
        src: PropTypes.string
    }

    static defaultProps = {
        webp: true
    }

    componentDidMount() {
        document.lazyLoadInstance.update()
    }

    componentDidUpdate(prevProps) {
        if (prevProps.src !== this.props.src) {  
            this.picRef.current && LazyLoad.resetStatus(this.picRef.current)
            this.imgRef.current && LazyLoad.resetStatus(this.imgRef.current)          
            document.lazyLoadInstance.update()
        }        
    }

    render() {
        const { alt, src, srcset, sizes, width, height, className, webp } = this.props        
        return (
            <picture>
                {
                    webp && <source 
                        ref={this.picRef}
                        className={`lazy ${className}`} 
                        type="image/webp" 
                        data-srcset={`${src}.webp`}
                    />
                }                    
                <img 
                    ref={this.imgRef}
                    alt={alt}
                    className={`lazy ${className}`}
                    data-src={src}
                    data-srcset={srcset}
                    data-sizes={sizes}
                    width={width}
                    height={height}
                />
                {this.props.children}
            </picture>
        )        
    }
}
